#include <p30F4011.h>
#include "settings.h"
#include "AC-Controller.h"
#include "globals.h"
#include "uart.h"

int counter1=0, i, j, streamOffset;
int asciiChar;


char serialStream[] =  {'F','B','=','x','x','x',' ',' ',	// fault_bits
						'I','b','=','x','x','x',' ',' ',	// i_b
						'I','A','=','x','x','x',' ',' ',	// i_alpha
						'I','B','=','x','x','x',0x0D,0x0A,	// i_beta
						'I','d','=','x','x','x',' ',' ',	// i_d
						'I','q','=','x','x','x',' ',' ',	// i_q
						'v','d','=','x','x','x',' ',' ',	// v_d_small
						'v','q','=','x','x','x',0x0D,0x0A,	// v_q_small
						'v','A','=','x','x','x',' ',' ',	// v_alpha
						'v','B','=','x','x','x',' ',' ',	// v_beta
						'r','1','=','x','x','x',' ',' ',	// Vr1
						'r','2','=','x','x','x',0x0D,0x0A,	// Vr2
						'r','3','=','x','x','x',' ',' ',	// Vr3
						'r','f','=','x','x','x',' ',' ',	// rotorFluxAngle
						'r','p','=','x','x','x',' ',' ',	// rotorPos
						'O','1','=','x','x','x',0x0D,0x0A,	// tempOffset1
						'O','2','=','x','x','x',' ',' ',	// tempOffset2
						't','c','=','x','x','x',' ',' ',	// tickCount
						'T','1','=','x','x','x',' ',' ',	// T1
						'T','2','=','x','x','x',0x0D,0x0A,	// T2
						'T','a','=','x','x','x',' ',' ',	// Ta
						'T','b','=','x','x','x',' ',' ',	// Tb
						'T','c','=','x','x','x',' ',' ',	// Tc
						'T','h','=','x','x','x',0x0D,0x0A,  // throttle_average
						't','1','=','x','x','x',' ',' ',	// totalTime:  Time the FOC code took.
						'O','C','=','x',0x0D,0x0A,0x0D,0X0A,0,0,0,0,0,0,0,0};  // overCurrentHasOccurred
int variable[26];	// Stores the variables that are going to be put in the serial stream.


// Use the uart for debugging
void InitUART2() {
    //U2BRG = (dFcy / (16 * Desired Baud)) - 1
	//U2BRG = (int)((long)dFcy / (16 * 19200)) - 1; // Pg. 506 on F.R.M.  Baud rate is 19200
	U2BRG = 64;
	U2MODE = 0;  // initialize to 0.
	U2MODEbits.PDSEL = 0b00; // 8 N 
	U2MODEbits.STSEL = 0; // 1 stop bit.
	U2MODEbits.UARTEN = 1; // enable the uart
	U2STAbits.UTXEN = 1; // Enable transmissions
}

int TransmitReady() {
	if (U2STAbits.UTXBF == 1) // Pg. 502 in F.R.M.  Is transmit buffer full?
		return 0;
	return 1; 
}

void SendCharacter(unsigned char ch) {
	// Make sure to run TransmitReady() before this.
	U2TXREG = ch;
}
